<script setup lang="ts">
/**
 * 账号验证流程：
 *
 * 1.获取到输入的电话号码及验证码
 *
 * 2.调用获取短信验证码接口
 *
 * 3.获取短信验证码之后，获取按钮需要暂时禁用
 *
 * 4.获取到验证码之后，下一步的时候校验验证码是否合法，如果合法则进入下一步
 *
 */
import { defineEmits, onUnmounted, reactive, ref } from 'vue'

import type { AxiosError, AxiosResponse } from 'axios'
import type { FormInstance, FormRules } from 'element-plus'
import { ElLoading, ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

import api from '@/utils/api'

// 路由控制七
const router = useRouter()

//自定义事件
const emit = defineEmits(['next'])
// 表单数据
const account = reactive({
  account: '',
  captcha: '',
  smscode: ''
})
//表单的实例
const formRef = ref()
//数据校验
const rules = reactive<FormRules<typeof account>>({
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  captcha: [{ required: true, message: '请输入图像验证码', trigger: 'blur' }],
  smscode: [{ required: true, message: '请输入短信验证码', trigger: 'blur' }]
})
//验证码
const captchaSrc = ref('/api/register/captcha')
//验证码的刷新
const refreshCaptcha = () => {
  captchaSrc.value = '/api/register/captcha?t_=' + new Date().getTime()
}
//定义定时器
let timer: number | undefined
//验证码倒计时
let smscodeTime = ref(0)
//获取短信验证码
const getSmscode = () => {
  if (!account.account || !account.captcha) {
    ElMessage.error('请输入电话号码及验证码')
    return
  }
  //显示加载动画
  const loading = ElLoading.service({
    lock: true,
    text: '正在处理',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  api
    .post('/api/register/getSmscode', {
      phone: account.account,
      captcha: account.captcha
    })
    .then((response: AxiosResponse<any>) => {
      if (response.status != 200 || !response.data || response.data.code != 200) {
        if (response.data) {
          ElMessage.error('获取失败:' + response.data.msg)
        } else {
          ElMessage.error('获取失败!')
        }
        return
      }
      //提示短信验证码已发送
      ElMessage({
        message: '短信验证码已发送，3分钟之内有效！',
        type: 'success'
      })
      //限制获取验证码按钮一分钟之内不能重复点击
      smscodeTime.value = 60
      timer = setInterval(() => {
        smscodeTime.value--
        if (smscodeTime.value <= 0) {
          smscodeTime.value = 0
          clearInterval(timer)
          timer = null
        }
      }, 1000)
    })
    .catch((error: AxiosError<any>) => {
      if (error.response && error.response.data) {
        ElMessage.error(error.response.data.msg)
        return
      }
      ElMessage.error('操作异常：' + error.message)
    })
    .finally(() => {
      loading.close()
    })
}
//提交表单
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((isValid: boolean) => {
    if (!isValid) {
      return
    }
    //显示加载动画
    const loading = ElLoading.service({
      lock: true,
      text: '正在处理',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    //请求接口，进行登陆
    api
      .post('/api/register/validateSmscode', {
        smscode: account.smscode
      })
      .then((response: AxiosResponse<any>) => {
        if (response.status != 200 || !response.data || response.data.code != 200) {
          if (response.data) {
            ElMessage.error('处理失败:' + response.data.msg)
          } else {
            ElMessage.error('处理失败!')
          }
          return
        }
        emit('next', {
          account: account.account,
          smscode: account.smscode,
          captcha: account.captcha
        })
      })
      .catch((error: AxiosError<any>) => {
        if (error.response && error.response.data) {
          ElMessage.error(error.response.data.msg)
          return
        }
        ElMessage.error('操作异常：' + error.message)
      })
      .finally(() => {
        loading.close()
      })
  })
}
//取消
const cancel = () => {
  router.push('/login')
}
onUnmounted(() => {
  //清除定时器
  timer && clearInterval(timer)
})
</script>

<template>
  <!-- 电话号码校验 -->
  <el-form
    ref="formRef"
    :model="account"
    :rules="rules"
    size="large"
    label-width="120"
    class="accountForm"
    status-icon
  >
    <el-form-item label="电话号码：" prop="account">
      <el-input v-model="account.account" placeholder="请输入电话号码" suffix-icon="UserFilled" />
    </el-form-item>
    <el-form-item label="图像验证码：" prop="captcha">
      <div class="flex">
        <div class="flexItem">
          <el-input v-model="account.captcha" placeholder="请输入图形验证码" />
        </div>
        <div class="captchaPanel">
          <img :src="captchaSrc" @click="refreshCaptcha" />
        </div>
      </div>
    </el-form-item>
    <el-form-item label="短信验证码：" prop="smscode">
      <div class="flex">
        <div class="flexItem">
          <el-input
            v-model="account.smscode"
            placeholder="请输入短信验证码"
            suffix-icon="Message"
          />
        </div>
        <div class="smscodePanel">
          <el-button @click="getSmscode" :disabled="smscodeTime > 0">{{
            smscodeTime > 0 ? smscodeTime + '秒之后再试' : '获取验证码'
          }}</el-button>
        </div>
      </div>
    </el-form-item>
    <el-form-item label="">
      <div class="formBtns">
        <el-button type="danger" @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm(formRef)"> 下一步 </el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<style scoped>
.accountForm {
  width: 50%;
  margin: 0 auto;
}

.accountForm .formBtns {
  margin: 0 auto;
}

.accountForm .formBtns .el-button {
  width: 150px;
}

.flex {
  display: flex;
  width: 100%;
}

.flex .flexItem {
  flex: 1;
}

.captchaPanel {
  width: 110px;
  padding-left: 10px;
}

.captchaPanel img {
  width: 100px;
  cursor: pointer;
}

.smscodePanel {
  width: 110px;
  padding-left: 10px;
}

.smscodePanel .el-button {
  width: 100px;
}
</style>
